<template>
  <view style="background: #fff">
    <view style="margin-top: 16rpx">
      <u-cell-group
        title="收货地址"
        :title-style="cellGroupTitleSty"
        :border="false"
      >
        <u-cell-item :arrow="false">
          <view class="custom-cell-label" slot="title">收货人</view>
          <view class="custom-cell-val" slot="right-icon"
            ><u-input
              v-model="receivingName"
              input-align="right"
              placeholder="请输入"
              :maxlength="20"
              trim
            ></u-input
          ></view>
        </u-cell-item>
        <u-cell-item :arrow="false">
          <view class="custom-cell-label" slot="title">收货电话</view>
          <view class="custom-cell-val" slot="right-icon">
            <u-input
              v-model="receivingPhone"
              input-align="right"
              placeholder="请输入"
              :maxlength="11"
              type="number"
              trim
            ></u-input>
          </view>
        </u-cell-item>
        <u-cell-item>
          <view class="custom-cell-label" slot="title">地区</view>
          <view class="custom-cell-val" slot="right-icon">
            <co-address-picker @change="addressPickerChange">
              <view
                class="region-text"
                :class="{ empty: !receivingLocation }"
                >{{ receivingLocation || '请选择' }}</view
              >
            </co-address-picker>
          </view>
        </u-cell-item>
        <view @click="toPosition"
          ><u-cell-item :arrow="false">
            <view class="custom-cell-label" slot="title">详细地址</view>
            <view class="custom-cell-val" slot="right-icon">
              <input
                v-model="receivingAddress"
                input-align="right"
                placeholder="输入详细地址，如街道、门牌号、写字楼、小区等"
                :maxlength="100"
                type="textarea"
                trim
              />
            </view> </u-cell-item
        ></view>
      </u-cell-group>
    </view>
    <!-- <view class="receiving-address">
      <template>
        <u-input
          type="textarea"
          v-model="getReceivingAddress"
          :height="250"
          :maxlength="100"
          placeholder="粘贴或输入文本，点击“识别”自动识别联系、收件人、联系电话、收货地"
          :custom-style="receivingAddressSty"
        ></u-input>
        <view
          class="receiving-address__btn"
          hover-class="receiving-address__btn-hover"
          @click.stop="addressTextGet"
          >识别</view
        >
      </template>
    </view> -->
    <view class="submit-button-wrap">
      <button
        class="co-primary-button u-reset-button am-block submit-button"
        hover-class="co-primary-button--hover"
        @click="submit"
      >
        提交
      </button>
    </view>
  </view>
</template>

<script>
import { apiAddressGet } from '@/api/common.js'
import { apiCustomerAdd, updateCustomer } from '@/api/customer'
import { UPDATE_CUSTOMER_LIST } from '@/types/globalEventName'
export default {
  data() {
    return {
      receivingName: '',
      receivingPhone: '',
      receivingLocation: '', // 省市区文字
      receivingAddress: '',
      cellGroupTitleSty: {
        background: '#FFFFFF',
        color: '#333',
        fontSize: '34rpx',
        fontWeight: 500
      },
      submitLoading: false,
      addressCode: [],
      detailInfo: {},
      getReceivingAddress: '',
      receivingAddressSty: {
        fontSize: '30rpx',
        color: '#333',
        lineHeight: '42rpx'
      }
    }
  },
  onLoad(option) {
    console.log(option)
    if (option.item) {
      this.detailInfo = JSON.parse(option?.item)
      this.receivingName = this.detailInfo.consigneeName
      this.receivingPhone = this.detailInfo.consigneePhone
      this.receivingAddress = this.detailInfo.consigneeAddress
      this.addressCode = [
        this.detailInfo.consigneeProvinceId,
        this.detailInfo.consigneeCityId,
        this.detailInfo.consigneeCountyId
      ]
      this.latitude = this.detailInfo.latitude
      this.longitude = this.detailInfo.longitude
      this.receivingLocation = `${this.detailInfo.consigneeProvince}-${this.detailInfo.consigneeCity}-${this.detailInfo.consigneeCounty}`
    }
  },
  methods: {
    toPosition(e) {
      // console.log(e, 'bindtapbindtapbindtapbindtap')
      // var that = this
      // uni.chooseLocation({
      //   success: function (lb) {},
      //   complete: function (lb) {
      //     that.latitude = lb.latitude
      //     that.longitude = lb.longitude
      //     that.receivingAddress = lb.name
      //     console.log(that.receivingAddress, '_++__+_++_++_+')
      //   },
      //   cancel: function (lb) {},
      //   fail: function (lb) {
      //     console.log(lb)
      //   }
      // })
    },
    submit() {
      console.log(this.customerPhone)
      if (this.submitLoading) return
      uni.showModal({
        title: '确认提交',
        content: '确认提交信息？',
        confirmColor: '#4BB019',
        success: (subRes) => {
          if (subRes.confirm) {
            uni.showLoading({
              mask: true
            })
            this.submitLoading = true
            let p_data = {}
            if (this.receivingName) {
              p_data.consigneeName = this.receivingName
            } else {
              this.$am_toast.error('请输入收货人')
              this.submitLoading = false
              return
            }
            if (this.receivingPhone) {
              p_data.consigneePhone = this.receivingPhone
            } else {
              this.$am_toast.error('请输入手机号')
              this.submitLoading = false
              return
            }
            if (this.receivingAddress) {
              p_data.consigneeAddress = this.receivingAddress
              p_data.latitude = this.latitude
              p_data.longitude = this.longitude
            } else {
              this.$am_toast.error('请输入地址')
              this.submitLoading = false
              return
            }
            if (this.addressCode.length !== 0) {
              p_data.consigneeProvinceId = this.addressCode[0]
              p_data.consigneeCityId = this.addressCode[1]
              p_data.consigneeCountyId = this.addressCode[2]
            } else {
              this.$am_toast.error('请选择地区')
              this.submitLoading = false
              return
            }
            if (this.detailInfo.id) {
              // 编辑
              updateCustomer({
                ...{
                  consigneeId: this.detailInfo.id
                },
                ...p_data
              })
                .then((res) => {
                  uni.hideLoading()
                  let { state, msg } = res.data
                  if (state === 'OK') {
                    console.log(12222)
                    uni.navigateBack({
                      delta: 1
                    })
                    uni.$emit(UPDATE_CUSTOMER_LIST)
                    this.$am_toast.success('编辑成功')
                  } else {
                    this.$am_toast.warning(msg)
                  }
                  this.submitLoading = false
                })
                .catch(() => {
                  this.submitLoading = false
                  uni.hideLoading()
                  this.$am_toast.error('操作失败，请重新尝试！')
                })
            } else {
              // 新增
              apiCustomerAdd(p_data)
                .then((res) => {
                  uni.hideLoading()
                  console.log(res)
                  let { state, msg } = res.data
                  if (state === 'OK') {
                    console.log(12222)
                    uni.navigateBack({
                      delta: 1
                    })
                    uni.$emit(UPDATE_CUSTOMER_LIST)
                    this.$am_toast.success('添加成功')
                  } else {
                    this.$am_toast.warning(msg)
                  }
                  this.submitLoading = false
                })
                .catch(() => {
                  this.submitLoading = false
                  uni.hideLoading()
                  this.$am_toast.error('操作失败，请重新尝试！')
                })
            }
          }
        }
      })
    },
    addressPickerChange(e) {
      console.log(e)
      this.receivingLocation = e.name.join('-')
      this.addressCode = e.code
    },
    // 地址识别
    addressTextGet() {
      if (!this.getReceivingAddress) {
        this.$am_toast('请输入内容！')
        return
      }
      uni.showLoading({
        mask: true
      })
      apiAddressGet({ str: this.getReceivingAddress })
        .then((res) => {
          let { state, msg, data } = res.data
          uni.hideLoading()
          if (state === 'OK') {
            this.receivingName = data.name
            this.receivingPhone = data.phone
            this.receivingAddress = data.address
            this.receivingLocation = `${data.provinceName}-${data.cityName}-${data.areaName}`
            this.addressCode = [data.provinceNo, data.cityNo, data.areaNo]
          } else {
            this.$am_toast.warning(msg)
          }
        })
        .catch(() => {
          uni.hideLoading()
          this.$am_toast.error('操作失败，请重新尝试！')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-cell-label {
  font-size: 30rpx;
  color: #666;
  &.required {
    &::after {
      content: '*';
      color: red;
    }
  }
}
.custom-cell-val {
  width: 450rpx;
  font-size: 30rpx;
  color: #333;
}
.region-text {
  height: 40rpx;
  line-height: 40rpx;
  text-align: right;
  color: #333;
  &.empty {
    color: #ccc;
  }
}
.submit-button-wrap {
  margin-top: 80rpx;
}
.submit-button {
  width: 690rpx;
  margin: 0 auto;
}
.receiving-address {
  position: relative;
  z-index: 10;
  margin: 26rpx 32rpx;
  background-color: #f5f5f5;
}
.receiving-address__btn {
  position: absolute;
  z-index: 30;
  right: 10%;
  bottom: 25rpx;
  width: 80%;
  height: 58rpx;
  line-height: 48rpx;
  text-align: center;
  background: #f7bb88;
  border-radius: 29px;
  font-size: 24rpx;
  color: #fff;
}
.receiving-address__btn-hover {
  opacity: 0.5;
}
</style>
